//
//  APViewController.m
//  MUPay
//
//  Created by 胡发冬 on 16/5/24.
//  Copyright © 2016年 胡发冬. All rights reserved.
//

#import "APViewController.h"
#import "Order.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>

@interface APViewController ()
{
    NSArray *body;
}
@end

@implementation APViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initialize];
    
    _productTableView.delegate=self;
    _productTableView.dataSource=self;
    
}
-(void)initialize{
     body = @[@"我是测试数据",
              @"我是测试数据",
              @"我是测试数据",
              @"我是测试数据",
              @"我是测试数据",
              @"我是测试数据",
              @"我是测试数据",
              @"我是测试数据",
              @"我是测试数据",
              @"我是测试数据"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)backBtn:(UIBarButtonItem *)sender {
    
    [self dismissViewControllerAnimated: YES completion: nil ];
}
#pragma mark -
#pragma mark   ==============产生随机订单号==============
- (NSString *)generateTradeNO
{
    static int kNumber = 15;
    
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand((unsigned)time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}
#pragma mark -
#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55.0f;
}
#pragma mark -
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [body count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                                   reuseIdentifier:@"Cell"];
    
    cell.textLabel.text = body[indexPath.row];
    cell.detailTextLabel.text = @"0.01";
    
    return cell;
}

#pragma mark -
#pragma mark   ==============点击订单模拟支付行为==============
//
//选中商品调用支付宝极简支付
//
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    /*
     *点击获取prodcut实例并初始化订单信息
     */

    
    /*
     *商户的唯一的parnter和seller。
     *签约后，支付宝会为每个商户分配一个唯一的 parnter 和 seller。
     */
    
    /*============================================================================*/
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
    NSString *partner = @"2088211626232100";
    NSString *seller = @"mibu@medicalunion.cn";
    NSString *privateKey = @"MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANfgID92KhyoCIffCGSAs+s4+hCpnj83vEvSBMUQ/XvRJbG4lnsJsISeo/LszYsReJIMOWLkMv7rekwLA2ANa4B+av1MphpgItjZh3rpNstk2sPIqD13tCQM9QEwN+Gj5cXEtdglmMIgo0LcM9pDIWS7UX1h0mRVAJQzyKCIFK6nAgMBAAECgYEA0+w5nDNTehhXb5M7OPbEKcoga1UofeUoW8KMXi2kuvWCLKsKRzUm7bqTNnrT+Y8oLzAC8hsWGP1wbNBu+s+R1KAsuVW0u51To2ugiVYgvuucR6aKg93YcAkNUAz0uNLp4/YmekPpqWh9CqM8Yl1hqopRy6bhoXIKovdQ2CHMqYECQQDuANWw3VVGjDk2dmONxp/fMyzZNWq/ysfP72MXn4ZIvxntod92luR5uOmch5n3ysXSvLxpbkQT8XFCOrloWqjnAkEA6DLzjIc/6Ld5wWEbJopWBl02Uh/QiFAfqM4U4rAazSr3E2kbAFjm+W1Zrmvucjq9Z2x/dN/fgiTizS/CwLxUQQJAI3sIYEd+sPeyh8X6bWZQ6wtMAk2OTm1CgGMlmJ31fN7QVLavA5TXFrZUTTuB3ojiGNp+FBGWIIr74W2zujTZvQJBALI/2uM4OIFnx9oBt5wAekVsbPTiY20hRQyLF1FmK0zw/Lcz6nx7wuQbY8sYI/YgzaGFktqfua7orgsh7PmUGYECQFQVzVqPPA3NyI8rZ6kKtjVh8C6CK4cxTtqr/bCIo6lqdqUmqRESayXqCNNSlJFxP+O0s8E9/GyAbySz3lwFKPE=";
    /*============================================================================*/
    /*============================================================================*/
    /*============================================================================*/
    
    //partner和seller获取失败,提示
    if ([partner length] == 0 ||
        [seller length] == 0 ||
        [privateKey length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少partner或者seller或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        return;
    }
    
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.sellerID = seller;
    order.outTradeNO = [self generateTradeNO]; //订单ID（由商家自行制定）
    order.subject = @"我是测试数据"; //商品标题
    order.body = @"我是测试数据-测试支付"; //商品描述
    order.totalFee = @"0.01"; //商品价格
    order.notifyURL =  @"http://www.xxx.com"; //回调URL
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showURL = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"mupay";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    NSLog(@"orderSpec = %@",orderSpec);
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            //NSLog(@"reslut = %@",resultDic);
        }];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}






/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
